import { useState, memo, useCallback, useMemo } from 'react'

type Child2Props = {
  user: { age: number }
}

const Child2 = memo(({ user }: Child2Props) => {
  console.log('Child2 组件更新')
  return (
    <div style={{ backgroundColor: '#abc', padding: 5 }}>
      子组件2 - 年龄： {user.age}
    </div>
  )
})

type ChildProps = {
  click: () => void
}

const Child = memo(({ click }: ChildProps) => {
  console.log('Child 组件更新')
  return (
    <div style={{ backgroundColor: 'skyblue', padding: 5 }}>
      子组件：<button onClick={click}>点击</button>
    </div>
  )
})

function UseMemo1 () {
  const [count, setCount] = useState(0)
  const [theme, setTheme] = useState('pink')

  const handleClick = useCallback(() => {
    console.log('你点击了子组件的按钮')
    setCount(count + 1)
  }, [count])

  // 使用 useMemo 来让该对象在组件更新期间保证引用相等
  // 注意：第一个参数（回调函数）的返回值，才表示要记住的数据
  // const user = useMemo(() => {
  //   return {
  //     age: 18
  //   }
  // }, [])

  // 演示：有依赖项的情况
  const user = useMemo(() => {
    console.log('useMemo 的回调函数执行了')
    return {
      age: count + 10
    }
  }, [count])

  return (
    <div style={{ backgroundColor: theme, padding: 10 }}>
      <button onClick={() => setTheme(theme === 'pink' ? 'white' : 'pink')}>
        切换主题
      </button>

      <h1>计数器：{count}</h1>
      <button onClick={() => setCount(count + 1)}>+1</button>

      <hr />

      {/* 子组件 */}
      <Child click={handleClick} />
      <br />
      <Child2 user={user} />
      {/* <Child2 user={{ age: 18 }} /> */}
    </div>
  )
}

export default UseMemo1
